package com.sojson.config.datasource.dynamic;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.sojson.config.datasource.dynamic.datasource.CustomDynamicRoutingDataSource;
import com.sojson.config.task.bean.TdHandler;
import com.sojson.util.ThreadLocalUtil;
import com.sojson.util.db.DbUtil;

/**
 * Dynamic配置类
 *
 * @author liu
 * @date 2022-01-11
 */
@Configuration
public class DynamicConfig {

    /**
     * 动态数据源配置项
     */
    @Autowired
    private DynamicDataSourceProperties properties;

    @Bean
    @Primary
    public DataSource customDynamicRoutingDataSource() {
        CustomDynamicRoutingDataSource dataSource = new CustomDynamicRoutingDataSource();
        dataSource.setPrimary(properties.getPrimary());
        dataSource.setStrict(properties.getStrict());
        dataSource.setStrategy(properties.getStrategy());
        dataSource.setP6spy(properties.getP6spy());
        dataSource.setSeata(properties.getSeata());
        DbUtil.setDataSource(dataSource);
        return dataSource;
    }

    /**
     * 线程装饰器,类似切面
     *
     * @return
     */
    @Bean
    public TdHandler<String> dynamicTdHandler() {
        TdHandler<String> handler = new TdHandler<String>() {

            @Override
            public void finallys() {
                DbUtil.clear();
            }

            @Override
            public int getSort() {
                return 3;
            }
        };
        ThreadLocalUtil.addHandler(handler);
        return handler;
    }

}